Page({
  data: {
    nickname: '',
    roomNumber: '',
    isCreatingRoom: false
  },

  // 输入昵称
  onNicknameInput(e) {
    this.setData({
      nickname: e.detail.value
    });
  },

  // 输入房间号
  onRoomNumberInput(e) {
    this.setData({
      roomNumber: e.detail.value
    });
  },

  // 创建房间
  async createRoom() {
    if (!this.data.nickname.trim()) {
      wx.showToast({
        title: '请输入昵称',
        icon: 'none'
      });
      return;
    }

    this.setData({ isCreatingRoom: true });
    
    // 使用回调方式的 wx.request
    wx.request({
      url: 'http://localhost:3000/api/room/create',
      method: 'POST',
      data: {
        nickname: this.data.nickname
      },
      // success 回调：当请求成功时，微信会调用这个函数
      success: (res) => {
        console.log("完整响应:", res);
        console.log("响应数据:", res.data);
        
        wx.setStorage({
          key: 'roomInfo',
          data: {
            roomNumber: res.data.room.roomNumber,
            userId: res.data.room.players[0].id
          },
          success: () => {
            wx.navigateTo({
              url: `/pages/room/room`
            });
          },
          fail:(error) =>
          {
            console.error("存储失败",error);
          }
        });
      },
      // fail 回调：当请求失败时，微信会调用这个函数
      fail: (error) => {
        console.error('创建房间错误:', error);
        wx.showToast({
          title: '创建房间失败',
          icon: 'none'
        });
      },
      // complete 回调：无论成功失败都会调用
      complete: () => {
        this.setData({ isCreatingRoom: false });
      }
    });
  },

  // 加入房间
  joinRoom() {
    if (!this.data.nickname.trim()) {
      wx.showToast({
        title: '请输入昵称',
        icon: 'none'
      });
      return;
    }

    if (!this.data.roomNumber.trim()) {
      wx.showToast({
        title: '请输入房间号',
        icon: 'none'
      });
      return;
    }

    wx.request({
      url: 'http://localhost:3000/api/room/join',
      method: 'POST',
      data: {
        nickname: this.data.nickname,
        roomNumber: this.data.roomNumber
      },
      success: (res) => {
        if (res.data.success) {
          // 存储房间信息和新分配的 userId
          wx.setStorage({
            key: 'roomInfo',
            data: {
              roomNumber: this.data.roomNumber,
              userId: res.data.room.players[res.data.room.players.length - 1].id,
              nickname: this.data.nickname
            },
            success: () => {
              wx.navigateTo({
                url: `/pages/room/room`
              });
            },
            fail: (error) => {
              console.error("存储失败", error);
            }
          });
        }
      },
      fail: (error) => {
        console.error('加入房间失败:', error);
        wx.showToast({
          title: '加入房间失败',
          icon: 'none'
        });
      }
    });
  },

  onShow() {
    // 检查是否有未过期的房间记录
    const lastRoom = wx.getStorageSync('lastRoom');
    if (lastRoom && lastRoom.roomNumber) {
      // 可以设置一个过期时间，比如30分钟
      const expireTime = 30 * 60 * 1000; // 30分钟
      if (Date.now() - lastRoom.timestamp < expireTime) {
        wx.redirectTo({
          url: '/pages/room/room'
        });
      } else {
        // 清除过期的房间记录
        wx.removeStorageSync('lastRoom');
      }
    }
  }
}); 